/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.user.web.teacher;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.beanvalidator.BeanValidators;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.sys.web.UserController;
import com.thinkgem.jeesite.modules.user.entity.teacher.TpPTeacher;
import com.thinkgem.jeesite.modules.user.service.teacher.TpPTeacherService;

/**
 * 老师Controller
 * @author 康力
 * @version 2018-03-10
 */
@Controller
@RequestMapping(value = "${adminPath}/user/teacher/tpPTeacher")
public class TpPTeacherController extends BaseController {
	@Autowired
	private UserController userController;
	@Autowired
	private TpPTeacherService tpPTeacherService;
	
	@Autowired
	private SystemService systemService;
	
	@ModelAttribute
	public TpPTeacher get(@RequestParam(required=false) String userId) {
		TpPTeacher entity = null;
		if (StringUtils.isNotBlank(userId)){
			entity = tpPTeacherService.get(userId);
			entity.setUser(systemService.getUser(userId));
		}
		if (entity == null){
			entity = new TpPTeacher();
		}
		return entity;
	}
	
	@RequiresPermissions("user:teacher:tpPTeacher:view")
	@RequestMapping(value = {"list", ""})
	public String list(TpPTeacher tpPTeacher, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(tpPTeacher.getOffice() == null )tpPTeacher.setOffice(UserUtils.getUser().getOffice());
		if(org.apache.commons.lang3.StringUtils.trimToNull(request.getParameter("flag")) != null){
//			tpPTeacher.setIsMasterTutor("1");
			tpPTeacher.setIsTutor(true);
		}
		Page<TpPTeacher> page = tpPTeacherService.findPage(new Page<TpPTeacher>(request, response), tpPTeacher); 
		model.addAttribute("page", page);
		model.addAttribute("flag", request.getParameter("flag"));
		return "modules/user/teacher/tpPTeacherList";
	}

	@RequiresPermissions("user:teacher:tpPTeacher:view")
	@RequestMapping(value = "form")
	public String form(TpPTeacher tpPTeacher, Model model, HttpServletRequest request) {
		model.addAttribute("tpPTeacher", tpPTeacher);
		model.addAttribute("allRoles", systemService.findAllRole());
		model.addAttribute("flag", request.getParameter("flag"));
		return "modules/user/teacher/tpPTeacherForm";
	}
	/**
	 * 老师修改个人信息
	 * @param tpPTeacher
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "info")
	public String info(TpPTeacher tpPTeacher,Model model, HttpServletRequest request) {
		User u = UserUtils.getUser();
		if(u == null){
			addMessage(model, "登录已失效，请重新登录！");
		}else {
			if(StringUtils.isNotBlank(tpPTeacher.getId())&&tpPTeacher.getUser()!=null){//保存
				if(tpPTeacher.getUser().getRoleList() == null || tpPTeacher.getUser().getRoleList().size() == 0){
					tpPTeacher.getUser().setRoleIdList(u.getRoleIdList());
				}
				tpPTeacherService.save(tpPTeacher);
			}
			tpPTeacher  = tpPTeacherService.get(u.getId());
			if(tpPTeacher == null)addMessage(model, "您不在教师库中，无法维护");
			else tpPTeacher.setUser(systemService.getUser(u.getId()));
		}
		model.addAttribute("tpPTeacher", tpPTeacher);
		return "modules/user/teacher/teacherInfo";
	}

	@RequiresPermissions("user:teacher:tpPTeacher:edit")
	@RequestMapping(value = "save")
	public String save(TpPTeacher tpPTeacher, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if (!beanValidator(model, tpPTeacher)){
			return form(tpPTeacher, model,request);
		}
		tpPTeacherService.save(tpPTeacher);
		addMessage(redirectAttributes, "保存老师成功");
		return "redirect:"+Global.getAdminPath()+"/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
	}
	
	@RequiresPermissions("user:teacher:tpPTeacher:edit")
	@RequestMapping(value = "delete")
	public String delete(TpPTeacher tpPTeacher, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		tpPTeacherService.delete(tpPTeacher);
		addMessage(redirectAttributes, "删除老师成功");
		return "redirect:"+Global.getAdminPath()+"/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
	}
	@RequiresPermissions("user:teacher:tpPTeacher:edit")
	@RequestMapping(value = "deleteBatch")
	public String deleteBatch(String userIds, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
		}
		User u = null;
		List<String> userIdArr = Arrays.asList(userIds.split(","));
		for(String userId : userIdArr){
			u = systemService.getUser(userId);
			StringBuffer message = new StringBuffer(100);
			if(redirectAttributes.getFlashAttributes().containsKey("message")){
				message.append(redirectAttributes.getFlashAttributes().get("message").toString());
			}
			if (UserUtils.getUser().getId().equals(u.getId())){
				addMessage(redirectAttributes, "删除教师用户"+u.getName()+"失败, 不允许删除当前用户;"+message.toString());
			}else if (User.isAdmin(u.getId())){
				addMessage(redirectAttributes, "删除教师用户"+u.getName()+"失败, 不允许删除超级管理员用户;"+message.toString());
			}else{
				TpPTeacher model = new TpPTeacher();
				model.setUser(u);
				tpPTeacherService.completelyDelete(model);
				addMessage(redirectAttributes, "删除教师用户"+u.getName()+"成功;"+message.toString());
			}
		}
		return "redirect:" + adminPath + "/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
	}
	
	/**
	 * 下载导入导师数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	/*@RequiresPermissions("user:teacher:tpPTeacher:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response,HttpServletRequest request, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "人员导入模板-教师.xlsx";
    		List<TpPTeacher> list = Lists.newArrayList(); list.add(new TpPTeacher());
    		new ExportExcel("教师信息", TpPTeacher.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
	    	String path = request.getSession().getServletContext()
	    			.getRealPath("/downloadExcel/"+fileName);
	    	response.setContentType("application/vnd.ms-excel;charset=GBK");
	    	response.addHeader("Content-Disposition", "attachment;filename="
	    			+ new String(fileName.getBytes("GBK"), "ISO8859_1"));
	    	OutputStream os = response.getOutputStream();
	    	File file = new File(path);
	    	FileInputStream fis = new FileInputStream(file);
	    	byte[] buffer = new byte[1024];
	    	int i = 0;
	    	while ((i = fis.read(buffer)) != -1) {
	    		os.write(buffer, 0, i);
	    	}
	    	fis.close();
	    	os.flush();
	    	os.close();
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/teacher/tpPTeacher/list?repage";
    }
	*/
	/**
	 * 下载导入用户数据模板
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:teacher:tpPTeacher:view")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		try {
			String fileName = "教师数据导入模板.xlsx";
			List<TpPTeacher> list = Lists.newArrayList();
			TpPTeacher teach=new TpPTeacher();
			teach.setUser(UserUtils.getUser());
			list.add(teach);
			new ExportExcel("教师数据", TpPTeacher.class, 2).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/student/tpPTeacher/list?flag="+request.getParameter("flag");
	}

	/**
	 * 导入用户数据
	 * @param file
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:teacher:tpPTeacher:view")
	@RequestMapping(value = "import", method= RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/user/teacher/tpPTeacher/?repage";
		}
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TpPTeacher> list = ei.getDataList(TpPTeacher.class);
			systemService.setFieldId(list);
			for (TpPTeacher teach : list){
				try{
					if ("true".equals(userController.checkLoginName("", teach.getUser().getLoginName()))){
						BeanValidators.validateWithException(validator, teach.getUser());
						tpPTeacherService.save(teach);
						successNum++;
					}else{
						User user=systemService.getUserByLoginName(teach.getUser().getLoginName());
						teach.setId(user.getId());
						teach.getUser().setId(user.getId());
						BeanValidators.validateWithException(validator, teach.getUser());
						tpPTeacherService.save(teach);
						failureMsg.append("<br/>登录名 "+teach.getUser().getLoginName()+"已更新; ");
						failureNum++;
					}
				}catch(ConstraintViolationException ex){
					failureMsg.append("<br/>登录名 "+teach.getUser().getLoginName()+" 导入失败：");
					List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
					for (String message : messageList){
						failureMsg.append(message+"; ");
						failureNum++;
					}
				}catch (Exception ex) {
					failureMsg.append("<br/>登录名 "+teach.getUser().getLoginName()+" 导入失败："+ex.getMessage());
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户，导入信息如下：");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条用户"+failureMsg);
		} catch (Exception e) {
			e.printStackTrace();
			addMessage(redirectAttributes, "导入用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
	}
	/**
	 * 导出用户数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("user:teacher:tpPTeacher:view")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(TpPTeacher tpPTeacher, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "教师用户数据"+ DateUtils.getDate("yyyy-MM-dd")+".xlsx";
//			Page<TpPTeacher> page = tpPTeacherService.findPage(new Page<TpPTeacher>(request, response, -1), tpPTeacher);
			new ExportExcel("教师用户数据", TpPTeacher.class).setDataList(tpPTeacherService.findList(tpPTeacher)).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出用户失败！失败信息："+e.getMessage());
		}
		return "redirect:" + adminPath + "/user/teacher/tpPTeacher/list?flag="+request.getParameter("flag");
	}

}